﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;

try
{
    Console.WriteLine("================消费者====================");
    Console.WriteLine("================消费者====================");
    Console.WriteLine("================消费者====================");

    string dir = AppDomain.CurrentDomain.BaseDirectory;
    //当前生产者名称
    string? consumerName = Path.GetFileName(Path.GetDirectoryName(dir));

    ConnectionFactory factory = new ConnectionFactory(); //创建链接的工厂
    factory.HostName = "43.142.250.100";//RabbitMQ服务在本地运行
    factory.UserName = "guest";//用户名
    factory.Password = "guest";//密码  
    factory.Port = 5672;
    using (IConnection connection = factory.CreateConnection()) //创建链接
    {
        using (var channel = connection.CreateModel())
        {
            Console.ForegroundColor = ConsoleColor.Green; //为了区分消息，设置一个输出控制台消息的颜色
            try
            {
                EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
                consumer.Received += (model, ea) =>  //如果有消息消费就触发这个事件
                { 
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body.ToArray());
                    Console.WriteLine($"{consumerName}: 接受消息: {message}");
                };
                channel.BasicConsume(queue: "OnlyProducerMessage",
                             autoAck: true,
                             consumer: consumer);
                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }


}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}